﻿using Christ3D.Domain.Interfaces;
using Christ3D.Infra.Data.Context;
using Christ3D.Infrastruct.UoW;

namespace Christ3D.Infra.Data.UoW
{
    /// <summary>
    /// 工作单元类
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private readonly DbSession _session;

        public UnitOfWork(DbSession session)
        {
            _session = session;
        }

        public void BeginTransaction()
        {
            _session.Transaction = _session.Connection.BeginTransaction();
        }

        public bool Commit()
        {
            try
            {
                _session.Transaction.Commit();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                Dispose();
            }
        }

        public void Rollback()
        {
            _session.Transaction.Rollback();
            Dispose();
        }

        public void Dispose() => _session.Transaction?.Dispose();
    }
}
